package com.uenpay.im.invokeitems;

import android.os.AsyncTask;
import android.text.TextUtils;

import com.qiyunxin.android.http.utils.StreamUtility;
import com.uenpay.im.callback.OnUploadFile2Listener;

import org.apache.http.HttpStatus;

import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class UploadFile {

	private OnUploadFile2Listener _onUploadFileListener;
	private String requestUrl;

	public UploadFile(byte[] fileData,
			OnUploadFile2Listener onUploadFileListener, String url) {
		_onUploadFileListener = onUploadFileListener;
		requestUrl = url;
		new FileUploadTask(fileData).execute();
	}

	private class FileUploadTask extends AsyncTask<Object, Integer, String> {
		byte[] toUploadData;

		public FileUploadTask(byte[] fileData) {
			toUploadData = fileData;
		}


		@Override
		protected String doInBackground(Object... params) {
			String response = "";
			String end = "\r\n";
			String boundary = "multipart/form-data; boundary=--------------------------7d03135102b8";
			try {
				
				URL url = new URL(requestUrl);
				HttpURLConnection con = (HttpURLConnection) url
						.openConnection();
				con.setDoInput(true);
				con.setDoOutput(true);
				con.setUseCaches(false);
				con.setRequestMethod("POST"); 
				con.setRequestProperty("Content-Type", boundary);
				DataOutputStream ds = new DataOutputStream(
						con.getOutputStream());
				ds.writeBytes("----------------------------7d03135102b8" + end);
				ds.writeBytes("Content-Disposition: form-data; name=\"uploadedFile\"; filename="
						+ System.currentTimeMillis() + ".jpg" + end);
				ds.writeBytes("Content-Type: application/octet-stream" + end);
				ds.writeBytes(end);
				ds.write(toUploadData);
				ds.writeBytes(end);
				ds.writeBytes("----------------------------7d03135102b8--"
						+ end);
				ds.flush();
				int statusCode = con.getResponseCode();

				if (statusCode == HttpStatus.SC_OK) {
					response = StreamUtility.readStream(con
							.getInputStream());
				} else {
					StringBuilder sb = new StringBuilder();
					sb.append("Upload image failed. ");
					sb.append("The http response status code is ");
					sb.append(statusCode);
					sb.append(". The request url is ");
					sb.append(url);
					// Logger.error("HttpInvokeEngine", sb.toString());
				}

			} catch (Exception e) {
				// Logger.error("UploadFileInvokeItem", "JSONException", e);
			}
			return response;
		}

		@Override
		protected void onPostExecute(String result) {
			if (TextUtils.isEmpty(result)) {
				_onUploadFileListener.OnUploadFileFail(result);
			} else {
				_onUploadFileListener.OnUploadFileSuccess(result);
			}
		}
	}
}
